<?php
	session_start();
	
	$userName;
	$userId;
	$response;
	$update;

	manageProfile();

	function manageProfile() {
		global $userName, $userId, $response, $update;

		$userName = $_SESSION['userName'];
		$update = $_GET['update'];
		$firstName = $_GET['firstName'];
		$lastName = $_GET['lastName'];

		$response = array (
			'update' => false,
			'getUserInfo' => false,
			'firstName' => null,
			'lastName' => null
		);

		$userExists = false;
		
		$userFile = fopen('../userInfo/users.txt', 'r') or die("can't open the user info file");
			while(($buffer = fgets($userFile)) != false){
				$user = explode(",", $buffer);
				if($userName == $user[0]){
					$userId = trim($user[1]);
					$userExists = true;
					break;
				}
			}
		fclose($userFile);
		
		if($userExists){
			updateUserInfo($firstName, $lastName);
		}

		echo json_encode($response);
	}


	function updateUserInfo($firstName = null, $lastName = null){
		global $userName, $userId, $response, $update;

		$userInfo = file("../userInfo/info.txt", FILE_SKIP_EMPTY_LINES);
		foreach($userInfo as $line_num => $user){
			$user = explode(",", $user);
			if(trim($user[2]) === $userId){
				if($update == "true"){
					$user[0] = $firstName;
					$user[1] = $lastName;
					$user = implode($user, ',');
					$userInfo[$line_num] = $user;
					$_SESSION['firstName'] = $firstName;
					$response['firstName'] = $firstName;
					break;
				}
				else{
					$response['firstName'] = $user[0];
					$response['lastName'] = $user[1];
					$response['getUserInfo'] = true;
				}
			}
		}
		if($update == "true"){
			$userInfo = implode($userInfo);
			rewriteUserInfoFile($userInfo);
		}
	}

	function rewriteUserInfoFile($userInfoString){
		global $response;
		$userInfoFile = fopen("../userInfo/info.txt", 'w+') or die("can't open user info file");
		fwrite($userInfoFile, $userInfoString);
		fclose($userInfoFile);
		$response['update'] = true;
	}
?>